import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
import { Index } from '../../apis/index.js';
const app = getApp();
const API = new Index();
const util = require("../../utils/util");
import { openBluetoothAdapterPeripheral } from '../../utils/bluetooth';
WXPage({
  data: {
    password: '*****',
    t: '',
    c: 0,
    deviceSn: "",
    isCtrip: false,
    productId: '',
    orderInfo: null,
    loginInfo: null,
    ruleInfo: '',
    scan: 0,
    loading: false,
    desc: '',
    showAd: 1,
    priceInfo: {},
    imageUrl: `${app.globalData.imageUrl}/images`,
    bluetoothType: wx.getStorageSync("bluetoothType")
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.setData({
      loading: true,
      isCtrip: app.globalData.isCtrip,
      deviceSn: app.globalData.deviceSn,
      scan: options.scan,
      showAd: wx.getStorageSync("showAd"),
      loginInfo: wx.getStorageSync('login_key')
    });
    if (!this.data.deviceSn) {
      this.setData({
        deviceSn: options.devicesn
      });
    }
    if (!this.data.loginInfo) {
      await API.getLoginToken().then(res => {
        this.setData({
          loginInfo: res.result
        });
        wx.setStorageSync("login_key", res.result);
      });
    }
    // 获取最新订单信息
    var param = {
      "deviceSn": this.data.deviceSn,
      "openid": this.data.loginInfo.openid
    };
    await API.checkOrderStatus(param).then(res => {
      res.result.beginAt = this.formatTime(res.result.beginAt);
      this.setData({
        orderInfo: res.result,
        productId: res.result.productId
      });
    });
    var useTimeParam = {
      "deviceSn": this.data.orderInfo.deviceSn,
      "productId": this.data.orderInfo.productId,
      "openid": this.data.loginInfo.openid,
      "tradeNo": this.data.orderInfo.tradeNo
    };
    await API.getUseTime(useTimeParam).then(res => {
      this.setData({
        t: util.usedTimeToMiniute(res.result)
      });
    });
    API.GetPriceDetail({
      "productId": this.data.orderInfo.productId
    }).then(res => {
      var priceInfo = res.result;
      var ruleInfo = '';
      if (this.data.orderInfo.feeMode === 2) {
        // 套餐模式
        ruleInfo = '(套餐)' + priceInfo.payMoney / 100 + '元' + '充电' + priceInfo.useDuration + '分钟';
      } else {
        if (priceInfo.freeTimes > 30) {
          ruleInfo = '前' + priceInfo.freeTimes + '分钟免费，之后' + priceInfo.payIntervalPrice / 100 + '元/小时';
        } else {
          // ruleInfo = priceInfo.basePrice/100 +  '元/' + priceInfo.baseTimes/60 + '小时' + '，' +  priceInfo.baseTimes/60 + '小时后(' + priceInfo.payIntervalPrice/100 + '元/每小时)'
          ruleInfo = '前' + priceInfo.baseTimes / 60 + '小时' + priceInfo.basePrice / 100 + '元，之后' + priceInfo.payIntervalPrice / 100 + '元/小时';
        }
      }
      this.setData({
        ruleInfo: ruleInfo,
        priceInfo
      });
    });
    this.setData({
      loading: false
    });
  },
  formatTime(timeAt) {
    return util.formatTimeMinute(new Date(timeAt * 1000));
  },
  // 蓝牙通知
  openBluetoothAdapterPeripheral(targetPowerMinute) {
    let {
      deviceTypeId,
      maxTime,
      useDuration
    } = this.data.priceInfo;
    let t = deviceTypeId === 10 ? maxTime : useDuration;
    let t1 = new Date().getTime() / 1000 - (Number(this.data.orderInfo.beginAt) || new Date(this.data.orderInfo.beginAt).getTime() / 1000);
    let powerMinute = parseInt(t - (t1 < 0 ? 0 : t1) / 60);
    console.log('恢复充电', powerMinute, this.data.priceInfo, this.data.orderInfo);
    let inPowerMinute = targetPowerMinute > 0 ? targetPowerMinute : powerMinute < 0 ? 0 : powerMinute;
    if (inPowerMinute > 1) wx.showLoading({
      title: '正在恢复充电',
      icon: 'loading',
      duration: 10000
    });
    openBluetoothAdapterPeripheral({
      bluetoothMac: app.globalData.bluetoothMac,
      powerMinute: inPowerMinute,
      success: res => {
        wx.hideLoading();
        if (inPowerMinute > 1) wx.showToast({
          title: '已恢复充电'
        });
        console.log('startAdvertising', res);
      },
      fail: err => {
        wx.hideLoading();
        
        console.log('inPowerMinute', inPowerMinute, this.data.bluetoothType)
        if (inPowerMinute > 1 && this.data.bluetoothType === 5) {
          return this.resetPassword('resetPassword')
        }
        
        if (inPowerMinute > 1) wx.showToast({
          title: '蓝牙连接失败,请重试',
          icon: 'none'
        });
        console.log('startAdvertising-error', err);
        // this.resetPassword('resetPassword')
      }
    });
  },

  // 获取密码
  getPassword: function () {
    var param = {
      "deviceSn": this.data.deviceSn,
      "productId": this.data.productId,
      "openid": this.data.loginInfo.openid
    };
    API.getPassword(param).then(res => {
      let data = res.result;
      var pwdInfo = data.password;
      if (data.useTime > 0) {
        this.setData({
          password: pwdInfo,
          t: data.useTime,
          c: data.count
        });
      }
    });
  },
  // 结束订单，结束使用
  closeOrder: function () {
    var loginInfo = wx.getStorageSync('login_key');
    var that = this;
    wx.showModal({
      title: '小电温馨提示',
      content: '充电结束后，请点击“立即归还”即可结束本次使用。小电速充祝您旅途愉快，欢迎下次光临!',
      cancelText: '继续使用',
      cancelColor: '#D3D3D3',
      confirmText: '立即归还',
      confirmColor: '#FF0000',
      success(res) {
        if (res.confirm) {
          if (app.globalData.bluetoothMac) that.openBluetoothAdapterPeripheral(1);
          var param = {
            "deviceSn": that.data.deviceSn,
            "productId": that.data.orderInfo.productId,
            "openid": loginInfo.openid,
            "tradeNo": that.data.orderInfo.tradeNo
          };
          API.closeOrder(param).then(res => {
            wx.redirectTo({
              url: '/pages/success/success?tradeno=' + that.data.orderInfo.tradeNo + '&deviceSn=' + that.data.orderInfo.deviceSn
            });
          });
        }
      }
    });
  },
  // 重置密码
  resetPassword(type) {
    console.log('resetPasswordFn', type)
    if (app.globalData.bluetoothMac && type !== 'resetPassword') {
      return this.openBluetoothAdapterPeripheral();
    }
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });
    var param = {
      "deviceSn": this.data.deviceSn,
      "productId": this.data.productId,
      "openid": this.data.loginInfo.openid,
      "tradeNo": this.data.orderInfo.tradeNo
    };
    API.resetPassword(param).then(res => {
      this.setData({
        password: res.result.password,
        t: 0,
        c: res.result.count
      });
    });
    wx.hideLoading();
  },
  showPwdCount: function (c) {
    wx.showModal({
      title: '还有 ' + c + ' 次刷新密码机会'
    });
  },
  // 故障申报
  handleReport: function () {
    var deviceSn = this.data.deviceSn;
    wx.navigateTo({
      url: '/pages/report/report?deviceSn=' + deviceSn
    });
  },
  onShow: function (e) {
    var that = this;
    if (!that.data.orderInfo) return;
    var param = {
      "deviceSn": that.data.deviceSn,
      "productId": that.data.orderInfo.productId,
      "openid": that.data.loginInfo.openid,
      "tradeNo": that.data.orderInfo.tradeNo
    };
    if (that.data.t === '' || that.data.orderInfo.productId !== '') {
      API.getUseTime(param).then(res => {
        this.setData({
          t: util.usedTimeToMiniute(res.result)
        });
      });
    } else {
      setInterval(function () {
        API.getUseTime(param).then(res => {
          that.setData({
            t: util.usedTimeToMiniute(res.result)
          });
        });
      }, 1000 * 60);
    }
  },
  // 联系客服
  openService: function () {
    wx.showActionSheet({
      itemList: ['使用帮助', '联系客服'],
      success: function (res) {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: '/pages/mine/help/help' // 使用帮助
          });
        }

        if (res.tapIndex === 1) {
          wx.makePhoneCall({
            phoneNumber: util.PHONE_NUMBER
          });
        }
      },
      fail: function (res) {
        console.log(res.errMsg);
      }
    });
  },
  // 足浴
  thirdPageGotoLavipeditum() {
    // wx.reportEvent("service_meituan_sanazuyu", {});
    if (this.data.devInfo.city === '武汉市') {
      wx.navigateTo({
        url: '/pages/webview/wyWebview/wyWebview'
      });
    } else if (this.data.devInfo.city === '衡阳市') {
      wx.navigateTo({
        url: '/pages/webview/eyWebview/eyWebview'
      });
    } else if (this.data.devInfo.city === '南宁市') {
      wx.navigateTo({
        url: '/pages/webview/xmNnWebview/xmNnWebview'
      });
    } else {
      wx.showToast({
        title: "目前该城市暂不支持",
        icon: "none"
      });
      return;
    }
  }
});
